package com.terry.activity.service.impl;

import com.terry.activity.bean.ActivityModel;
import com.terry.activity.bean.exception.DataNotExistException;
import com.terry.activity.dao.IActivityDao;
import com.terry.activity.service.IActivityService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * Create On 18/6/17.
 *
 * @author TerrySolar
 */
@Service("ActivityService")
public class ActivityServiceImpl implements IActivityService {

    @Resource
    private IActivityDao activityDao;

    @Override
    public ActivityModel setVoteTimeRange(Long activityId, Long startTime, Long endTime) throws DataNotExistException {

        ActivityModel activityModel;

        try {
            activityModel = this.activityDao.findById(activityId).get();
        } catch (NoSuchElementException e) {
            throw new DataNotExistException("活动不存在！");
        }

        activityModel.setVoteStartTime(startTime);
        activityModel.setVoteEndTime(endTime);

        return this.activityDao.save(activityModel);
    }

    @Override
    public ActivityModel getActivity(Long activityId) throws DataNotExistException {

        try {
            return this.activityDao.findById(activityId).get();
        } catch (NoSuchElementException e) {
            throw new DataNotExistException("活动不存在！");
        }
    }

    @Override
    public List<ActivityModel> getActivity() {
        return this.activityDao.findAll();
    }

    @Override
    public ActivityModel updateActivity(ActivityModel activityModel) throws DataNotExistException {

        try {
            ActivityModel old = this.activityDao.findById(activityModel.getId()).get();
            old.setBrief(activityModel.getBrief());
            old.setTitle(activityModel.getTitle());
            old.setEnable(activityModel.getEnable());
            return this.activityDao.save(old);
        } catch (NoSuchElementException e) {
            throw new DataNotExistException("活动不存在!");
        }
    }

    @Override
    public ActivityModel addActivity(ActivityModel activityModel) {
        return this.activityDao.save(activityModel);
    }
}
